from selenium import webdriver  
from selenium.webdriver.common.by import By  
from selenium.webdriver.support.ui import WebDriverWait  
from selenium.webdriver.support import expected_conditions as EC  
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys
import json

def openMiguHtml(miguUrl):
    # 创建浏览器驱动对象  

    driver = webdriver.Safari() # 使用Chrome浏览器为例  
    driver.maximize_window()  # 浏览器全屏
    # 打开目标网页  
    # 西甲集锦：皇马vs马洛卡
    #ul = 'https://www.miguvideo.com/p/live/120000459675'
    driver.get(miguUrl) 
    print('开始打开url')
    return driver


def scrollToElement(driver, element) :
    driver.execute_script("arguments[0].scrollIntoView();", element)


# 模拟点击元素
def clickElement(driver, element) :

    scrollToElement(driver, element)
    time.sleep(1)

    # 获取鼠标指针的当前位置  
    mouse_position = driver.execute_script("return {x: window.screenX, y: window.screenY}")  
    
    # 构建鼠标点击的动作链  
    actions = ActionChains(driver)  
    actions.move_to_element(element)  # 将鼠标指针移动到div元素的位置  
    actions.click()  # 触发点击事件 
    # 执行动作链并等待点击事件完成  
    actions.perform() 



#保存json文件
def saveJsonFile(gameJsonPath, jsonData) :
    
    with open(gameJsonPath, "w", encoding='utf-8') as file:  
        #file.write(json_data)
        json.dump(jsonData, file, ensure_ascii=False, indent=4)
        print('保存json数据完成')


def getPlayListArr(driver) :
	playlistDic = []
	# 找到当前页面所有的歌单列表（会包含其他元素，所以需要过滤下）
	divList = driver.find_elements(By.CSS_SELECTOR, ".item.item")
	if len(divList) > 0 :
		for div in divList :
			divtext = div.text
			textlen = len(div.text)
			print(f'得到div文本：{divtext}')
			#如果文本长度>2，并且文本包含换行 和 万字样
			seperateChar = ' '  #谷歌浏览器是换行
			if textlen > 2 and seperateChar in divtext and '万' in divtext :
				#确认找到歌单后，在过滤一次，只 要包含经典的
				print(f"找到歌单：{divtext}")
				if '经典' in divtext :
					print('找到经典歌单')

					print('查找封面图')
					cover = ''
					imgs = div.find_elements(By.TAG_NAME, "img")
					if len(imgs) > 0 :
						cover = imgs[0].get_attribute('src')
						print("点击一下封面，获取歌单id")
						# imgs[0].click();
						# clickElement(driver, imgs[0])
						div.click()
						time.sleep(2)


						itemid = ''
						itemid_divs = driver.find_elements(By.ID, "myDiv") 
						if len(itemid_divs) > 0 :
							itemid = itemid_divs[-1].text 
							print(f"找到itemid: {itemid}")
						if len(itemid) < 3 :
							print("获取itemid 失败，过滤")
							continue;

						# time.sleep(500)
					#用换行分割得到 名称 与播放量
					txtArr = divtext.split(seperateChar)
					if len(txtArr) >= 1 :
						playDic = {'title':txtArr[0],'playCount':txtArr[1],'cover':cover,'itemID':itemid}
						playlistDic.append(playDic)

						if len(playlistDic) > 1 :
							break;

	print('\n\n得到解析结果：\n')
	print(playlistDic)
	return playlistDic

#歌单详情页 数字为itemID
#https://www.kuwo.cn/playlist_detail/3573968657
def start() :
	driver = openMiguHtml('http://www.kuwo.cn/playlists')

	# 移除广告弹窗
	ar = driver.find_elements(By.CSS_SELECTOR, ".model_out")
	if len(ar) > 0 :
		driver.execute_script("arguments[0].style.display = 'none';", ar[-1])
	time.sleep(3)
	print("广告弹窗移除完成")

	#找到 最热 的a标签，然后点击一下
	aaas = driver.find_elements(By.CSS_SELECTOR, 'a[data-v-17ae183a]')
	for aa in aaas :
		if '最热' in aa.text :
			clickElement(driver, aa)
			# aa.click()
			print('点击最热结束，等待3秒')
			break;
	
	time.sleep(3)
	datas = []
	# 爬取10页
	for i in range(10) :

		#获取当前页
		pageNum = '0'
		currPages = driver.find_elements(By.CSS_SELECTOR, ".notCursor.currentPage")
		if len(currPages) > 0 :
			pageNum = currPages[0].text
			print(f"当前页：{pageNum}")

		dicArr = getPlayListArr(driver)
		if len(dicArr) > 0 :
			datas = datas + dicArr

		#找到下一页元素，然后点击
		nextPages = driver.find_elements(By.CSS_SELECTOR, ".li-page.iconfont.icon-icon_pagedown")
		if len(nextPages) > 0 :
			print('得到下一页')
			# nextPages[0].click()
			clickElement(driver, nextPages[0])
			print('点击了下一页, 等待3秒')
			time.sleep(3)


	saveJsonFile('./data.json', datas)
	print(f"\n\n爬取完成：共{len(datas)}歌单")
	print("\n5秒后退出")
	time.sleep(5)


start()









